package com.github.littleantfly.dictionary;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ser.DictSerializerModifier;
import com.github.littleantfly.dictionary.config.DictProperties;
import com.github.littleantfly.dictionary.service.DictService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;

@Configuration
@ConditionalOnClass(MappingJackson2HttpMessageConverter.class)
public class JacksonDictAutoConfiguration implements InitializingBean {
    private final static Logger logger = LoggerFactory.getLogger(JacksonDictAutoConfiguration.class);
    private final MappingJackson2HttpMessageConverter converter;
    private final DictProperties dictProperties;
    private final DictService dictService;

    public JacksonDictAutoConfiguration(MappingJackson2HttpMessageConverter converter, DictProperties dictProperties, DictService dictService) {
        this.converter = converter;
        this.dictProperties = dictProperties;
        this.dictService = dictService;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        ObjectMapper mapper = converter.getObjectMapper();
        mapper.setSerializerFactory(mapper.getSerializerFactory().withSerializerModifier(new DictSerializerModifier(dictService, dictProperties)));
        if(logger.isDebugEnabled()) {
            logger.debug("init JacksonDictAutoConfiguration");
        }
    }
}
